package Array;

import org.junit.Test;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Array
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-20  21:49
 * @Description: TODO
 * @Version: 1.0
 */
public class 反转字符串中的单词15 {
    // 直接使用分割 然后倒叙遍历实现 需要空间复杂O(n) 时间也是O(n)
    public String reverseWords(String s) {
        String[] split = s.trim().split(" ");
        String result="";
        for (int i = split.length-1; i >=0; i--) {
            if (!"".equals(split[i])) {
                result+=split[i]+" ";
            }
        }
        return result.trim();
    }

    // 请尝试使用 O(1) 额外空间复杂度的 原地解法。 java 里面实现不了
    public String reverseWords2(String s) {
        StringBuilder sb = trimSpaces(s);

        // 翻转字符串
        reverse(sb, 0, sb.length() - 1);

        // 翻转每个单词
        reverseEachWord(sb);

        return sb.toString();
    }

    // 去除' ' 字符
    public StringBuilder trimSpaces(String s) {
        int left = 0, right = s.length() - 1;
        // 去掉字符串开头的空白字符
        while (left <= right && s.charAt(left) == ' ') {
            ++left;
        }

        // 去掉字符串末尾的空白字符
        while (left <= right && s.charAt(right) == ' ') {
            --right;
        }

        // 将字符串间多余的空白字符去除
        StringBuilder sb = new StringBuilder();
        while (left <= right) {
            char c = s.charAt(left);

            if (c != ' ') {
                sb.append(c);
            } else if (sb.charAt(sb.length() - 1) != ' ') {
                sb.append(c);
            }

            ++left;
        }
        return sb;
    }

    // 实现自定字符串的反转
    public void reverse(StringBuilder sb, int left, int right) {
        while (left < right) {
            char tmp = sb.charAt(left);
            sb.setCharAt(left++, sb.charAt(right));
            sb.setCharAt(right--, tmp);
        }
    }

    public void reverseEachWord(StringBuilder sb) {
        int n = sb.length();
        int start = 0, end = 0;

        while (start < n) {
            // 循环至单词的末尾
            while (end < n && sb.charAt(end) != ' ') {
                ++end;
            }
            // 翻转单词
            reverse(sb, start, end - 1);
            // 更新start，去找下一个单词
            start = end + 1;
            ++end;
        }
    }

    @Test
    public void test() {
        String theSkyIsBlue = reverseWords("the sky is blue");

        String key="the sky is blue";
        StringBuilder sb=new StringBuilder(key);
        sb.reverse();
        System.out.println(sb.toString());
        int left=0;
        int right=sb.length()-1;
        while (left<right){
            Character c=sb.charAt(left);
            sb.setCharAt(left++,sb.charAt(right));
            sb.setCharAt(right--,c);
        }
        System.out.println(sb.toString());
    }
}
